/*
* Powered By [choudou5]
* Web Site: http://www.hsolr.com
* License：MIT
* Since 2018 - 2020
*/
package com.choudou5.solr.service.client;

import com.choudou5.solr.annotation.ServiceInfo;
import com.choudou5.solr.bean.client.SolrClientAuth;
import com.choudou5.solr.framework.constants.CacheConsts;
import com.choudou5.solr.framework.constants.SysConsts;
import com.choudou5.solr.service.BaseService;
import com.choudou5.solr.util.cache.CacheFactory;
import com.choudou5.solr.util.cache.impl.LRUCache;
import com.choudou5.solr.util.exception.BizException;
import com.choudou5.solr.util.jdbc.SqlFormatUtil;

/**
 * @name 客户端授权 Service
 * @author choudou5
 * @date：2018-08-06
 */
@ServiceInfo(table = "solr_client_auth", desc = "客户端授权")
public class SolrClientAuthService extends BaseService<SolrClientAuth> {

    private static final LRUCache<String, SolrClientAuth> CACHE = CacheFactory.newLRUCache(10);

    @Override
    public void update(SolrClientAuth bean) {
        super.update(bean);
        removeCache(bean.getAppKey());
    }

    public String getAppKey(Integer id) throws BizException {
        SolrClientAuth bean = get(id);
        String appKey = bean==null?null:bean.getAppKey();
        String appName = bean==null?null:bean.getAppName();
        addSynDynamic(SysConsts.ActionType.VIEW, "查看了 "+appName+" 应用的appKey");
        return appKey;
    }


    public SolrClientAuth getByAppKey(String appKey) throws BizException {
        String cacheKey = CacheConsts.API_APP + appKey;
        SolrClientAuth apiApp = CACHE.get(cacheKey);
        if(apiApp != null)
            return apiApp;
        String where = "status = 1 AND app_key = ?";
        apiApp = findOne(SqlFormatUtil.format(where, appKey));
        if(apiApp == null)
            return null;
        CACHE.put(cacheKey, apiApp);
        return apiApp;
    }

    public void removeCache(String appKey) {
        String cacheKey = CacheConsts.API_APP + appKey;
        CACHE.remove(cacheKey);
    }
}